#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
练习题统计脚本

统计练习题系统的完整情况，包括题目数量、知识点覆盖、完成度等。
"""

import os
import re
from pathlib import Path
from collections import defaultdict, Counter

def count_files_in_directory(directory):
    """统计目录中的文件数量"""
    if not os.path.exists(directory):
        return 0
    return len([f for f in os.listdir(directory) if f.endswith('.py') and f.startswith('exercise_')])

def count_solutions_in_directory(directory):
    """统计解答目录中的文件数量"""
    if not os.path.exists(directory):
        return 0
    return len([f for f in os.listdir(directory) if f.endswith('.py') and f.startswith('solution_')])

def extract_knowledge_points(file_path):
    """从练习题文件中提取知识点"""
    knowledge_points = []
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 查找知识点标记
        patterns = [
            r'知识点[：:](.*?)\n',
            r'涉及知识[：:](.*?)\n',
            r'学习目标[：:](.*?)\n',
            r'# 知识点[：:](.*?)\n',
        ]
        
        for pattern in patterns:
            matches = re.findall(pattern, content, re.IGNORECASE)
            for match in matches:
                points = [p.strip() for p in match.split(',') if p.strip()]
                knowledge_points.extend(points)
                
    except Exception as e:
        pass
        
    return knowledge_points

def analyze_difficulty_distribution():
    """分析难度分布"""
    levels = {
        'level_01_basics': '🟢 初级',
        'level_02_intermediate': '🟡 中级', 
        'level_03_advanced': '🟠 高级',
        'level_04_expert': '🔴 专家级'
    }
    
    stats = {}
    total_exercises = 0
    total_solutions = 0
    
    for level_dir, level_name in levels.items():
        exercise_count = count_files_in_directory(level_dir)
        solution_count = count_solutions_in_directory(f'solutions/{level_dir}')
        
        stats[level_name] = {
            'exercises': exercise_count,
            'solutions': solution_count,
            'completion': f"{solution_count}/{exercise_count}" if exercise_count > 0 else "0/0"
        }
        
        total_exercises += exercise_count
        total_solutions += solution_count
    
    return stats, total_exercises, total_solutions

def analyze_knowledge_points():
    """分析知识点覆盖"""
    all_knowledge_points = []
    
    # 遍历所有练习题文件
    for level_dir in ['level_01_basics', 'level_02_intermediate', 'level_03_advanced', 'level_04_expert']:
        if os.path.exists(level_dir):
            for file_name in os.listdir(level_dir):
                if file_name.endswith('.py') and file_name.startswith('exercise_'):
                    file_path = os.path.join(level_dir, file_name)
                    points = extract_knowledge_points(file_path)
                    all_knowledge_points.extend(points)
    
    # 统计知识点频率
    knowledge_counter = Counter(all_knowledge_points)
    return knowledge_counter

def get_file_stats():
    """获取文件统计信息"""
    stats = {
        'total_files': 0,
        'python_files': 0,
        'markdown_files': 0,
        'total_lines': 0
    }
    
    for root, dirs, files in os.walk('.'):
        # 跳过隐藏目录和__pycache__
        dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']
        
        for file in files:
            if file.startswith('.'):
                continue
                
            file_path = os.path.join(root, file)
            stats['total_files'] += 1
            
            if file.endswith('.py'):
                stats['python_files'] += 1
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        stats['total_lines'] += len(f.readlines())
                except:
                    pass
            elif file.endswith('.md'):
                stats['markdown_files'] += 1
    
    return stats

def print_banner():
    """打印横幅"""
    print("="*70)
    print("📊 Python学习练习题集 - 统计报告")
    print("="*70)
    print()

def print_difficulty_stats(stats, total_exercises, total_solutions):
    """打印难度统计"""
    print("🎚️ 难度级别统计:")
    print("-" * 50)
    
    for level_name, data in stats.items():
        completion_rate = (data['solutions'] / data['exercises'] * 100) if data['exercises'] > 0 else 0
        print(f"{level_name:<12} | 练习题: {data['exercises']:>2} | 解答: {data['solutions']:>2} | 完成度: {completion_rate:>5.1f}%")
    
    print("-" * 50)
    overall_completion = (total_solutions / total_exercises * 100) if total_exercises > 0 else 0
    print(f"{'📈 总计':<12} | 练习题: {total_exercises:>2} | 解答: {total_solutions:>2} | 完成度: {overall_completion:>5.1f}%")
    print()

def print_knowledge_stats(knowledge_counter):
    """打印知识点统计"""
    print("🧠 知识点覆盖统计:")
    print("-" * 50)
    
    if knowledge_counter:
        # 显示前10个最常见的知识点
        top_points = knowledge_counter.most_common(10)
        for point, count in top_points:
            print(f"  📌 {point:<25} ({count} 次)")
        
        print(f"\n  💡 总计 {len(knowledge_counter)} 个不同知识点")
    else:
        print("  ⚠️  未找到知识点标记")
    
    print()

def print_file_stats(file_stats):
    """打印文件统计"""
    print("📁 文件统计:")
    print("-" * 50)
    print(f"  📄 总文件数: {file_stats['total_files']}")
    print(f"  🐍 Python文件: {file_stats['python_files']}")
    print(f"  📝 Markdown文件: {file_stats['markdown_files']}")
    print(f"  📏 总代码行数: {file_stats['total_lines']:,}")
    print()

def print_structure_overview():
    """打印结构概览"""
    print("🏗️ 项目结构概览:")
    print("-" * 50)
    
    structure_items = [
        ("📖 README.md", "完整使用指南和项目介绍"),
        ("🚀 QUICKSTART.md", "5分钟快速入门指南"),
        ("🎯 demo.py", "交互式演示脚本"),
        ("🧪 test_exercises.py", "自动化测试和验证系统"),
        ("📊 stats.py", "统计分析脚本 (本脚本)"),
        ("🟢 level_01_basics/", "初级练习题 (基础语法)"),
        ("🟡 level_02_intermediate/", "中级练习题 (高级特性)"),
        ("🟠 level_03_advanced/", "高级练习题 (设计模式)"),
        ("🔴 level_04_expert/", "专家级练习题 (系统架构)"),
        ("✅ solutions/", "完整解答和最佳实践"),
    ]
    
    for item, description in structure_items:
        print(f"  {item:<25} {description}")
    
    print()

def print_learning_progress():
    """打印学习进度建议"""
    print("📈 学习进度建议:")
    print("-" * 50)
    
    progress_items = [
        ("第1-2周", "🟢 Level 1", "掌握Python基础语法 (1-20题)"),
        ("第3-5周", "🟡 Level 2", "理解高级语法特性 (21-40题)"),
        ("第6-9周", "🟠 Level 3", "掌握复杂项目开发 (41-60题)"),
        ("第10-15周", "🔴 Level 4", "具备架构设计能力 (61-80题)"),
    ]
    
    for time_range, level, description in progress_items:
        print(f"  {time_range:<8} | {level} | {description}")
    
    print()

def print_quick_commands():
    """打印快速命令"""
    print("⚡ 快速命令:")
    print("-" * 50)
    
    commands = [
        ("python demo.py", "运行交互式演示"),
        ("python test_exercises.py", "运行所有测试"),
        ("python test_exercises.py --level 1", "测试Level 1练习题"),
        ("python test_exercises.py --benchmark", "性能基准测试"),
        ("python stats.py", "查看统计报告 (本命令)"),
    ]
    
    for command, description in commands:
        print(f"  {command:<35} # {description}")
    
    print()

def main():
    """主函数"""
    # 切换到脚本所在目录
    os.chdir(Path(__file__).parent)
    
    print_banner()
    
    # 难度统计
    difficulty_stats, total_exercises, total_solutions = analyze_difficulty_distribution()
    print_difficulty_stats(difficulty_stats, total_exercises, total_solutions)
    
    # 知识点统计
    knowledge_counter = analyze_knowledge_points()
    print_knowledge_stats(knowledge_counter)
    
    # 文件统计
    file_stats = get_file_stats()
    print_file_stats(file_stats)
    
    # 结构概览
    print_structure_overview()
    
    # 学习进度
    print_learning_progress()
    
    # 快速命令
    print_quick_commands()
    
    print("🎉 统计完成！开始你的Python学习之旅吧！")
    print("="*70)

if __name__ == "__main__":
    main()
